<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeft, ArrowRight, Location, Timer } from '@element-plus/icons-vue'
import { getShopById } from '@/api/shop'
import { getVoucherList, seckillVoucher } from '@/api/voucher'
import { useUserStore } from '@/stores'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const rate = ref(4.5)

// 响应式数据
const shop = ref({})
const vouchers = ref([])

// 获取店铺详情
const queryShopById = async (shopId) => {
  try {
    const { data } = await getShopById(shopId)
    console.log('getShopByIddata', data)
    data.images = data.images.split(',')
    shop.value = data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取店铺详情失败')
  }
}

// 获取优惠券列表
const queryVoucher = async (shopId) => {
  try {
    const { data } = await getVoucherList(shopId)
    vouchers.value = data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取优惠券列表失败')
  }
}

// 格式化时间
const formatTime = (v) => {
  const b = new Date(v.beginTime)
  const e = new Date(v.endTime)
  return (
    b.getMonth() +
    1 +
    '月' +
    b.getDate() +
    '日 ' +
    b.getHours() +
    ':' +
    formatMinutes(b.getMinutes()) +
    ' ~ ' +
    e.getHours() +
    ':' +
    formatMinutes(e.getMinutes())
  )
}

// 格式化分钟
const formatMinutes = (m) => {
  if (m < 10) m = '0' + m
  return m
}

// 格式化价格
const formatPrice = (price) => {
  return price.toFixed(2)
}

// 判断是否未开始
const isNotBegin = (v) => {
  return new Date(v.beginTime).getTime() > new Date().getTime()
}

// 判断是否已结束
const isEnd = (v) => {
  return new Date(v.endTime).getTime() < new Date().getTime()
}

// 秒杀抢购
const seckill = async (v) => {
  if (!userStore.token) {
    ElMessage.error('请先登录')
    setTimeout(() => {
      router.push('/login')
    }, 200)
    return
  }

  if (isNotBegin(v)) {
    ElMessage.error('优惠券抢购尚未开始！')
    return
  }

  if (isEnd(v)) {
    ElMessage.error('优惠券抢购已经结束！')
    return
  }

  if (v.stock < 1) {
    ElMessage.error('库存不足，请刷新再试试！')
    return
  }

  try {
    const { data } = await seckillVoucher(v.id)
    ElMessage.success('抢购成功，订单id：' + data)
  } catch (error) {
    console.error(error)
    ElMessage.error('抢购失败')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 过滤后的优惠券列表
const filteredVouchers = computed(() => {
  return vouchers.value.filter((v) => !isEnd(v))
})

// 初始化
onMounted(() => {
  const shopId = route.params.id
  console.log('shopId', shopId)
  queryShopById(shopId)
  queryVoucher(shopId)
})
</script>

<template>
  <div class="shop-detail-container">
    <!-- 头部 -->
    <div class="header">
      <div class="header-back-btn" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="header-title"></div>
      <div class="header-share">...</div>
    </div>

    <!-- 店铺信息 -->
    <div class="shop-info-box">
      <div class="shop-title">{{ shop.name }}</div>
      <div class="shop-rate">
        <el-rate
          v-model="shop.score"
          disabled
          :max="5"
          :value="shop.score / 10"
          text-color="#F63"
          show-score
        />
        <span>{{ shop.comments }}条</span>
      </div>
      <div class="shop-rate-info">口味:4.9 环境:4.8 服务:4.7</div>
      <div class="shop-rank">
        <img src="/src/assets/imgs/bd.png" width="63" height="20" alt="" />
        <span>拱墅区好评榜第3名</span>
        <div>
          <el-icon><ArrowRight /></el-icon>
        </div>
      </div>
      <div class="shop-images">
        <div v-for="(s, i) in shop.images" :key="i">
          <img :src="s" alt="" />
        </div>
      </div>
      <div class="shop-address">
        <div>
          <el-icon><Location /></el-icon>
        </div>
        <span>{{ shop.address }}</span>
        <div
          style="width: 10px; flex-grow: 2; text-align: center; color: #e1e2e3"
        >
          |
        </div>
        <div style="margin: 0 5px">
          <img
            src="https://p0.meituan.net/travelcube/bf684aa196c870810655e45b1e52ce843484.png@24w_16h_40q"
            alt=""
          />
        </div>
        <div>
          <img
            src="https://p0.meituan.net/travelcube/9277ace32123e0c9f59dedf4407892221566.png@24w_24h_40q"
            alt=""
          />
        </div>
      </div>
    </div>

    <div class="shop-divider"></div>

    <!-- 营业时间 -->
    <div class="shop-open-time">
      <span>
        <el-icon><Timer /></el-icon>
      </span>
      <div>营业时间</div>
      <div>{{ shop.openHours }}</div>
      <span class="line-right">
        查看详情
        <el-icon><ArrowRight /></el-icon>
      </span>
    </div>

    <div class="shop-divider"></div>

    <!-- 优惠券 -->
    <div class="shop-voucher">
      <div>
        <span class="voucher-icon">券</span>
        <span style="font-weight: bold">代金券</span>
      </div>
      <div class="voucher-box" v-for="v in filteredVouchers" :key="v.id">
        <div class="voucher-circle">
          <div class="voucher-b"></div>
          <div class="voucher-b"></div>
          <div class="voucher-b"></div>
        </div>
        <div class="voucher-left">
          <div class="voucher-title">{{ v.title }}</div>
          <div class="voucher-subtitle">{{ v.subTitle }}</div>
          <div class="voucher-price">
            <div>￥ {{ formatPrice(v.payValue) }}</div>
            <span>{{ (v.payValue * 10) / v.actualValue }}折</span>
          </div>
        </div>
        <div class="voucher-right">
          <div v-if="v.type" class="seckill-box">
            <div
              class="voucher-btn"
              :class="{ 'disable-btn': isNotBegin(v) || v.stock < 1 }"
              @click="seckill(v)"
            >
              限时抢购
            </div>
            <div class="seckill-stock">
              剩余 <span>{{ v.stock }}</span> 张
            </div>
            <div class="seckill-time">{{ formatTime(v) }}</div>
          </div>
          <div class="voucher-btn" v-else>抢购</div>
        </div>
      </div>
    </div>

    <div class="shop-divider"></div>

    <!-- 评论 -->
    <div class="shop-comments">
      <div class="comments-head">
        <div>网友评价 <span>（119）</span></div>
        <div>
          <el-icon><ArrowRight /></el-icon>
        </div>
      </div>
      <div class="comment-tags">
        <div class="tag">味道赞(19)</div>
        <div class="tag">牛肉赞(16)</div>
        <div class="tag">菜品不错(11)</div>
        <div class="tag">回头客(4)</div>
        <div class="tag">分量足(4)</div>
        <div class="tag">停车方便(3)</div>
        <div class="tag">海鲜棒(3)</div>
        <div class="tag">饮品赞(3)</div>
        <div class="tag">朋友聚餐(6)</div>
      </div>
      <div class="comment-list">
        <div class="comment-box" v-for="i in 3" :key="i">
          <div class="comment-icon">
            <img
              src="https://p0.meituan.net/userheadpicbackend/57e44d6eba01aad0d8d711788f30a126549507.jpg%4048w_48h_1e_1c_1l%7Cwatermark%3D0"
              alt=""
            />
          </div>
          <div class="comment-info">
            <div class="comment-user">叶小乙 <span>Lv5</span></div>
            <div style="display: flex">
              打分
              <el-rate disabled v-model="rate"></el-rate>
            </div>
            <div style="padding: 5px 0; font-size: 14px">
              某平台上买的券，价格可以当工作餐吃，虽然价格便宜，但是这家店一点都没有...
            </div>
            <div class="comment-images">
              <img
                src="https://qcloud.dpfile.com/pc/6T7MfXzx7USPIkSy7jzm40qZSmlHUF2jd-FZUL6WpjE9byagjLlrseWxnl1LcbuSGybIjx5eX6WNgCPvcASYAw.jpg"
                alt=""
              />
              <img
                src="https://qcloud.dpfile.com/pc/sZ5q-zgglv4VXEWU71xCFjnLM_jUHq-ylq0GKivtrz3JksWQ1f7oBWZsxm1DWgcaGybIjx5eX6WNgCPvcASYAw.jpg"
                alt=""
              />
              <img
                src="https://qcloud.dpfile.com/pc/xZy6W4NwuRFchlOi43DVLPFsx7KWWvPqifE1JTe_jreqdsBYA9CFkeSm2ZlF0OVmGybIjx5eX6WNgCPvcASYAw.jpg"
                alt=""
              />
              <img
                src="https://qcloud.dpfile.com/pc/xZy6W4NwuRFchlOi43DVLPFsx7KWWvPqifE1JTe_jreqdsBYA9CFkeSm2ZlF0OVmGybIjx5eX6WNgCPvcASYAw.jpg"
                alt=""
              />
            </div>
            <div>浏览641 &nbsp;&nbsp;&nbsp;&nbsp;评论5</div>
          </div>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            padding: 15px 0;
            border-top: 1px solid #f1f1f1;
            margin-top: 10px;
          "
        >
          <div>查看全部119条评价</div>
          <div>
            <el-icon><ArrowRight /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <div class="shop-divider"></div>

    <div class="copyright">copyright ©2021 hmdp.com</div>
  </div>
</template>

<style scoped>
.shop-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-back-btn {
  padding: 5px;
  cursor: pointer;
}

.header-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.header-share {
  padding: 5px;
  cursor: pointer;
}

.shop-info-box {
  padding: 15px;
  background-color: #fff;
}

.shop-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.shop-rate {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.shop-rate-info {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.shop-rank {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.shop-images {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  overflow-x: auto;
}

.shop-images img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.shop-address {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.shop-divider {
  height: 10px;
  background-color: #f5f5f5;
}

.shop-open-time {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
}

.shop-open-time > div {
  margin-left: 10px;
}

.line-right {
  margin-left: auto;
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
}

.shop-voucher {
  padding: 15px;
  background-color: #fff;
}

.voucher-icon {
  background-color: #f63;
  color: #fff;
  padding: 2px 5px;
  border-radius: 2px;
  margin-right: 5px;
}

.voucher-box {
  display: flex;
  margin-top: 10px;
  background-color: #fff;
  border: 1px solid #f1f1f1;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}

.voucher-circle {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.voucher-b {
  width: 10px;
  height: 10px;
  background-color: #f5f5f5;
  border-radius: 50%;
}

.voucher-left {
  flex: 1;
  padding: 10px;
  border-right: 1px dashed #f1f1f1;
}

.voucher-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.voucher-subtitle {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.voucher-price {
  color: #f63;
  font-size: 16px;
  display: flex;
  align-items: baseline;
  gap: 5px;
}

.voucher-right {
  width: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f63;
  color: #fff;
}

.voucher-btn {
  padding: 5px 15px;
  border: 1px solid #fff;
  border-radius: 15px;
  cursor: pointer;
}

.disable-btn {
  opacity: 0.5;
  cursor: not-allowed;
}

.seckill-box {
  text-align: center;
}

.seckill-stock {
  font-size: 12px;
  margin: 5px 0;
}

.seckill-time {
  font-size: 12px;
}

.shop-comments {
  padding: 15px;
  background-color: #fff;
}

.comments-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.comment-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.tag {
  padding: 5px 10px;
  background-color: #f5f5f5;
  border-radius: 15px;
  font-size: 14px;
}

.comment-box {
  display: flex;
  margin-bottom: 15px;
}

.comment-icon img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.comment-info {
  flex: 1;
}

.comment-user span {
  color: #666;
  font-size: 12px;
  margin-left: 5px;
}

.comment-images {
  display: flex;
  gap: 5px;
  margin: 10px 0;
}

.comment-images img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.copyright {
  text-align: center;
  padding: 15px;
  color: #999;
  font-size: 12px;
}
</style>
